<template>
  <div class="update-avatar">
      <img :src="img" alt="" ref="img">
    <div class="toolbar">
      <span class="cancel" @click="$emit('close')">取消</span>
      <span class="confirm" @click="confirm">完成</span>
    </div>
  </div>
</template>

<script>
import { updateUserAvatar } from '@/api/user.js'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  props: {
    img: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: 'move', // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false // 关闭默认背景
    })
  },
  methods: {
    confirm () {
      // console.log(this.cropper.getData())
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        console.log(blob)
        this.$toast.loading({
          message: '加载中...',
          forbidClick: true,
          loadingType: 'spinner',
          duration: 0
        })
        try {
          const formData = new FormData()
          formData.append('photo', blob)
          const { data } = await updateUserAvatar(formData)
          console.log(data)
          this.$emit('close')
          this.$emit('updataphoto', data.data.photo)
          this.$toast.success('修改成功')
        } catch (err) {
          this.$toast.fail('修改失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.update-avatar {
  background-color: #000;
  height: 100%;
  img {
    height: 100%;
     max-width: 100%;
  }
  .toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  .cancel, .confirm {
    padding-left: 15px ;
    width: 90px;
    height: 90px;
     display: flex;
     justify-content: space-between;
     align-items:center;
    font-size: 30px;
    color: #fff;
  }
  }
}
</style>
